# -*- coding: utf-8 -*-
"""
@Author: Logan
@Date:   2025/7/11 16:41
@Description: 
"""
import redis
from config.yaml_config import GetConf


class RedisOperation:
    def __init__(self):
        redis_info = GetConf().get_redis()
        print(f"初始化 Redis 连接，配置: {redis_info}")

        # 显式检查每个字段（处理类型转换问题）
        self.host = redis_info.get("host")
        self.port = redis_info.get("port")
        self.db = redis_info.get("db")

        # 验证字段存在且合法
        if not self.host:
            raise ValueError("缺少 Redis host 配置")
        if self.port is None:
            raise ValueError("缺少 Redis port 配置")
        if self.db is None:
            raise ValueError("缺少 Redis db 配置")

        # 确保 port 和 db 是数字类型
        try:
            self.port = int(self.port)
            self.db = int(self.db)
        except (ValueError, TypeError):
            raise ValueError("Redis port 或 db 必须是数字")

        # 初始化 Redis 客户端
        try:
            self.redis_client = redis.Redis(
                host=self.host,
                port=self.port,
                db=self.db,
                password=redis_info.get("password"),
                decode_responses=True,
                socket_timeout=5,
            )
            print("Redis 客户端初始化成功")
        except Exception as e:
            print(f"Redis 客户端初始化失败: {e}")
            raise


if __name__ == "__main__":
    redis_op = RedisOperation()
    print(redis_op.redis_client)
    # 显式测试连接（关键！）
    response = redis_op.redis_client.ping()
    print(f"连接成功，PING 响应: {response}")